package com.sztu.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.sztu.mapper.TeacherMapper;
import com.sztu.pojo.Teacher;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TeacherServiceImpl implements TeacherService{
    @Autowired
    TeacherMapper teacherMapper;
    @Override
    public List<Teacher> getAllTeacher() {
        return teacherMapper.getAllTeacher();
    }

    @Override
    public List<Teacher> queryTeacher(Map map) {
        return teacherMapper.queryTeacher(map);
    }

    @Override
    public int addTeacher(Map map) {
        return teacherMapper.addTeacher(map);
    }

    @Override
    public int delTeacherById(Integer id) {
        return teacherMapper.delTeacherById(id);
    }

    @Override
    public int updateTeacher(Map map) {
        return teacherMapper.updateTeacher(map);
    }

    @Override
    public Workbook exportExcel() {
        List teacherList=teacherMapper.getAllTeacher();
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("教师表","教师"),Teacher.class,teacherList);
        return workbook;
    }

    @Override
    public Integer importExcel(File file) {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        List<Teacher> teacherList = ExcelImportUtil.importExcel(file, Teacher.class, params);
        for (Teacher teacher:teacherList){
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("id",teacher.getId());
            map.put("name",teacher.getName());
            map.put("account",teacher.getAccount());
            map.put("authority",teacher.getAuthority());
            map.put("password",teacher.getPassword());
            map.put("cid",teacher.getCollege().getId());
            try {
                if(teacherMapper.updateTeacher(map)!=1){
                    teacherMapper.addTeacher(map);
                }
            }catch (Exception e){
                return 0;
            }
        }
        return 1;
    }
}
